﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web;
using System.Web.Security;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Configuration;
using System.Web.Script.Serialization;
namespace eDoc.BO
{
    public class RequestAuthen
    {
        public RequestAuthen()
        {

        }
        public string username { get; set; }
        public string password { get; set; }
    }
    public class ResponseAuthen
    {
        public ResponseAuthen()
        {

        }

        public string UserName { get; set; }
        public string FullName { get; set; }
        public string Email { get; set; }
        public string Title { get; set; }
        public string Code { get; set; }
        public string Status { get; set; }
        public string MessageError { get; set; }
    }
    public class Sescurity
    {
        private string SignInToken = "SigninToken";
        public const string UserRoleAdmin = "admin";
        private readonly static string AuthenUrl = ConfigurationManager.AppSettings["AuthenUrl"];

        public static bool Login(string email, string pass)
        {
           
                RequestAuthen requestAuthen = new RequestAuthen
                {
                    password = pass,
                    username = email
                };
                ResponseAuthen result = new ResponseAuthen();
                var serializer = new JavaScriptSerializer();
                string serializedResult = serializer.Serialize(requestAuthen);
                serializedResult = HttpUtility.UrlEncode(serializedResult);
                string data = get_web_content(AuthenUrl + serializedResult);
                if (!string.IsNullOrEmpty(data))
                {
                    result = serializer.Deserialize<ResponseAuthen>(data);
                }
                if (result.Status == "SUCCESS")
                    return true;
                return false;
           
        }

        private static string get_web_content(string url)
        {

            Uri uri = new Uri(url);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method = WebRequestMethods.Http.Get;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader reader = new StreamReader(response.GetResponseStream());

            string output = reader.ReadToEnd();

            response.Close();

            return output;

        }

        /// <summary>
        /// Lay ID cac menu ma user duoc quyen truy cap
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string GetMenuID(string username)
        {
            string value = "";

            DataTable dt = new DataTable();
            dt = Data.Select_User_Menu(username);
            if (dt != null && dt.Rows.Count > 0)
            {
                value = dt.Rows[0]["Menu_ID"].ToString();
            }

            return value;
        }

        public void SetAuthCookie(HttpContext httpContext, FormsAuthenticationTicket authenticationTicket, string CookieName)
        {
            var encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket);
            var cookie = new HttpCookie(CookieName, encryptedTicket);
            cookie.HttpOnly = true;
            cookie.Expires = authenticationTicket.Expiration;
            httpContext.Response.Cookies.Add(cookie);
        }

        public void UserSignIn(AuthenUser authenUser, HttpContext _curentHttpContext)
        {
            //var user = new AuthenUser
            //{
            //    Email = email,
                
            //    Username = username
            //};
            var loginToken = new FormsAuthenticationTicket(1, SignInToken, DateTime.Now, DateTime.Now.AddMinutes(30), true, JsonConvert.SerializeObject(authenUser));
            SetAuthCookie(_curentHttpContext, loginToken, SignInToken);
        }

        public bool CheckLogin(HttpContext _curentHttpContext)
        {
            var LoginTokenCookie = _curentHttpContext.Request.Cookies[SignInToken];
            if (LoginTokenCookie != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public AuthenUser CurrentUser(HttpContext _curentHttpContext)
        {
            AuthenUser userApp = null;
            var LoginTokenCookie = _curentHttpContext.Request.Cookies[SignInToken];
            if (LoginTokenCookie != null)
            {
                try
                {
                    var token = FormsAuthentication.Decrypt(LoginTokenCookie.Value);
                    userApp = JsonConvert.DeserializeObject<AuthenUser>(token.UserData);

                }
                catch
                {
                    return null;
                }
            }
            return userApp;
        }
        public void SignOutLocal(HttpContext httpContext)
        {
            var cookie = new HttpCookie(SignInToken);
            DateTime nowDateTime = DateTime.Now;
            cookie.Expires = nowDateTime.AddDays(-1);
            httpContext.Response.Cookies.Add(cookie);
        }
        
    }

    public class AuthenUser
    {
        public AuthenUser()
        {

        }
        public string Email { get; set; }
        public string Username { get; set; }
        public int AppMode { get; set; }
    }
}
